<?php
/**
 * Created by JieHuiLong.
 * E-mail: jiehuilong@icloud.com
 * Date: 2016/8/16
 * Time: 16:00
 * 广告分组管理控制器
 */

namespace App\Http\Controllers\Admin;

use App\Models\DomainAttributes;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Http\Requests\GroupCreateRequest;
use App\Http\Requests\GroupUpdateRequest;
use App\Models\Group;
use App\Models\GroupAttributes as GroupAttr;
use App\Models\Domain;
use App\Models\Templates;
use App\Models\DomainAttributes as DomainAttr;
use App\Models\Wechat;
use App\Models\WechatGroup;
use App\Models\Term;

use App\Models\AdminUser as User;
use Cache,Config,DB;

class GroupController extends Controller
{
    protected $fields = [
        'uid' => 1,
        'username' => '',
        'title' => '',
        'directory' => '/',
        'go_to_type' => 0,
        'go_to_type_title' => '',
        'target_gid' => 0,
        'target_gname' => '',
        'tpl_id' => 0,
        'template' => '',
        'sh_tpl_id' => 0,
        'sh_template' => '',
        'area_config' => 0,
        'area_list' => '',
        'device_type' => 0,
        //'station_type' => 0,
        'channel' => '',
        'wechat_list' => '',
		 'ips' => '',
		'source'=>'',
		'delivery_time' => '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23', 
		'wechat_ids'=>'',
		'term_id'=>[0],
		'sh_term_id'=>'0',
    ];

    /**
     * 根据requst 返回分组列表数据
     *
     * @return Json
     */
    public function __construct(Request $request)
    {
        $this->uid 		= auth()->user()->id;
        $this->username = auth()->user()->name;
    }
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data 					= array();
            $data['draw'] 			= $request->get('draw');
            $start 					= $request->get('start');
            $length 				= $request->get('length');
            $order 					= $request->get('order');
            $columns 				= $request->get('columns');
            $search 				= $request->get('search');
            $data['recordsTotal'] 	= Group::where(session('authAdminCondition'))->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] 	= Group::where(function ($query) use ($search) {
                    $query->where('title', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('template', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))->count();
                $data['data'] 				= Group::where(function ($query) use ($search) {
                    $query->where('title', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('template', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] 	= $data['recordsTotal'];
                $data['data'] 				= Group::where(session('authAdminCondition'))
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);

        }

        return view('admin.group.index');
    }

    /**
     * 新建数据
     *
     * @return array $data
     */
    public function create()
    {
        $data 					= [];
        foreach ($this->fields as $field => $default) {
            $data[$field] 		= old($field, $default);
        }

        $data['wechats'] 		= Wechat::where('uid',$this->uid)->where('status',1)->select('wx_num','wx_nike','max_rand','online_time','offline_time')->get();
        $data['userList'] 		= User::lists('name', 'id');
        $data['templateList'] 	= Templates::where('uid',$this->uid)->lists('name', 'id');
        $data['groupList'] 		= Group::where(session('authAdminCondition'))->lists('title', 'id');
		//$data['delivery_times']	= config('app.delivery_time');
		//$data['delivery_value'] = config('app.delivery_time');
		$uid 					= $this->uid;
		$wechatgroup1 			= WechatGroup::select("wechat_groups.id","wechat_groups.name")
									->join('wechat_group_users','wechat_group_users.gid','=','wechat_groups.id')
									->where(function($query)use($uid){
										$query->where('wechat_group_users.uid',$uid);
									})->get()->toArray();
		$wechatgroup2 			= WechatGroup::select("wechat_groups.id","wechat_groups.name")->where('wechat_groups.uid',$this->uid)->get()->toArray();
		$data['wechatgroup'] 	= array_merge($wechatgroup1,$wechatgroup2);
		$wechat_groups_ids 		= WechatGroup::getWechatGroupCids($this->uid,'id');
		$data['wechats'] 		= Wechat::select("id","wx_num","group",'wx_nike','status')
									->where(function ($query) use ($wechat_groups_ids){
										$query->orWhereIn('group',$wechat_groups_ids);
									})
									->get()->toArray();
		$data['terms'] 			= Term::where('aid',$this->uid)->where('status',1)->get();
		$data['tpls'] 			= [0];
		$data['template']		= [''];
		$data['term_id']		= [0];
        return view('admin.group.create', $data);
    }

    /**
     * 向数据表新增一条记录
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(GroupCreateRequest $request)
    {
        $group 					= new Group();
        foreach (array_keys($this->fields) as $field) {
			if($field=='tpl_id'||$field=='template'||$field=='term_id'){
				$tpl_ids 		= $request->get($field);
				$str 			= "";
				foreach($tpl_ids as $tpl_id){
					$str 		.= $tpl_id.",";
				}
				$str 			= substr($str,0,strlen($str)-1); 
				$group->$field 	= $str;
				continue;
			}
            $group->$field 		= $request->get($field);
        }
        $checkId 				= Group::where(["title" => $group->title,"directory" => $group->directory, "uid" => $this->uid])->value('id');
        if ($checkId) {
            return back()->withErrors('添加失败！【分组名】不能重复，请您使用其他分组名');
        }
        $group->save();
        if($group->id){
            $item['uid'] 		= $this->uid;
            $item['username'] 	= $this->username;
            $item['gid'] 		= $group->id;
            $item['gname'] 		= $group->title;
            $item['type'] 		= '多行文本';
            $item['type_value'] = 'text';
            $item['created_at'] = date('Y-m-d H:i:s');
            $defaultAttr = array("顶部菜单","底部版权信息","统计代码");
            foreach ($defaultAttr as $key => $obj){
                $item['name'] 	= $obj;
                $item['call_tag'] 	= $obj;
                $data[] 		= $item;
            }
            if(!empty($data))GroupAttr::insert($data);
        }

		event(new \App\Events\userActionEvent('\App\Models\Group',$group->id, 1, '新增了分组['.$group->title.']' ));
        return redirect('/admin/group')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 编辑数据
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $group					=	Group::find((int)$id);
        if (!$group) return redirect('/admin/group')->withErrors("找不到该分组!");
        foreach (array_keys($this->fields) as $field) {
            $data[$field]		=	old($field,$group->$field);
        }
		$uid					=	auth()->user()->id;
        $data['id'] 			= 	(int)$id;
        $data['groupId'] 		= 	$group->id;
        $data['userList'] 		= 	User::lists('name', 'id');
        $data['groupList'] 		= 	Group::where('uid',auth()->user()->id)->lists('title', 'id');
        $data['templateList'] 	= 	Templates::where('uid',auth()->user()->id)->lists('name', 'id');
		$data['wechat_list']	== 	null ? [] : $data['wechat_list'];
		$wechatgroup1 			= 	WechatGroup::select("wechat_groups.id","wechat_groups.name")
										->join('wechat_group_users','wechat_group_users.gid','=','wechat_groups.id')
										->where(function($query)use($uid){
											$query->where('wechat_group_users.uid',$uid);
										})->get()->toArray();
		$wechatgroup2 			= 	WechatGroup::select("wechat_groups.id","wechat_groups.name")->where('wechat_groups.uid',$uid)->get()->toArray();
		$data['wechatgroup'] 	= 	array_merge($wechatgroup1,$wechatgroup2);
		$wechat_groups_ids 		= 	WechatGroup::getWechatGroupCids(auth()->user()->id,'id');
		$data['wechats'] 		= 	Wechat::select("id","wx_num","group",'wx_nike','status')
										->where(function ($query) use ($wechat_groups_ids){
											$query->orWhereIn('group',$wechat_groups_ids);
										})
										->get()->toArray();
		$data['terms'] 			= 	Term::where('aid',$uid)->where('status',1)->get();
		$data['tpls']			= 	explode(',',$group->tpl_id);
		$data['template']		=	explode(',',$group->template);
		$data['term_id']		= 	explode(',',$group->term_id);
        return view('admin.group.edit', $data);
    }

    /**
     * 更新数据
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(GroupUpdateRequest $request, $id)
    {
        $group 					= 	Group::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
			if($field=='tpl_id'||$field=='template'||$field=='term_id'){
				$tpl_ids 		= $request->get($field);
				$str 			= "";
				foreach($tpl_ids as $tpl_id){
					$str 		.= $tpl_id.",";
				}
				$str 			= substr($str,0,strlen($str)-1); 
				$group->$field 	= $str;
				continue;
			}
            $group->$field		=	$request->get($field);
        }
        if($request->title != $group->title && $request->directory != $group->directory){
            $checkId 			= 	Group::where(["title" => $group->title,"directory" => $group->directory, "uid" => $this->uid])->value('id');
            if ($checkId) {
                return back()->withErrors('添加失败！【分组名】不能重复，请您使用其他分组名');
            }
        }
        $group->save();
        if ($request->cover === 'cover') {
            //  对应配置进行覆盖
            $coverData['gname'] 			= $group->title;
            $coverData['go_to_type'] 		= $group->go_to_type;
            $coverData['go_to_type_title'] 	= $group->go_to_type_title;
            $coverData['directory'] 		= $group->directory;
            $coverData['target_gid'] 		= $group->target_gid;
            $coverData['target_gname'] 		= $group->target_gname;
            $coverData['tpl_id'] 			= $group->tpl_id;
            $coverData['template'] 			= $group->template;
            Domain::where('gid', '=', $group->id)->update($coverData);
        }
		$userToken	= Cache::rememberForever('userToken', function () {
				$tokenUid 		= auth()->user()->id;
				$token 			= DB::table('tokens');
				$userToken 		= $token->where('uid', '=', $tokenUid)->value('token');
				if ($userToken === null) {
					$userToken 	= $this->createToken($tokenUid);
				}
				return $userToken;
			});
			$domains 			= Domain::where('gid',$group->id)->get();
			foreach($domains as $domain){
				$this->crossUpTpl2($domain->id,$domain->tpl_id,$userToken);
			}
		event(new \App\Events\userActionEvent('\App\Models\Group',$id, 3, '更新分组['.$group->title.']'));
        return redirect('/admin/group')->withSuccess('更新成功！');
    }

    /**
     * 删除数据
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(is_numeric($id)){
            $tag	= Group::find((int)$id);
            if ($tag) {
				$title	= $tag->title;
                $tag->delete();
                Domain::where('gid', $id)->delete();
                DomainAttr::where('gid', $id)->delete();
                GroupAttr::where('gid', $id)->delete();
				event(new \App\Events\userActionEvent('\App\Models\Group',$id, 2, '删除分组['.$title.']'));
            } else {
                return redirect()->back()->withErrors("删除失败");
            }
        }else{
            $idArr	= explode(',',$id);
			$titles	= '';
			$gs		= Group::whereIn('id',$idArr)->get();
			foreach($gs as $g){ 
				$titles	.= $g->title."、";
			}
			$recordRow 	= Group::whereIn('id',$idArr)->delete();
			Domain::where('gid', $idArr)->delete();
			DomainAttributes::where('gid', $idArr)->delete();
			event(new \App\Events\userActionEvent('\App\Models\Group',0, 2, '删除分组['.$titles.']'));
			if(!$recordRow){
				return redirect()->back()->withErrors("删除失败");
            }
        }
        return redirect()->back()->withSuccess("删除成功");
    }
	public function crossUpTpl2($id,$tpl_id,$userToken){
		if (config('app.debug')) {
			return redirect()->back()->withErrors("请叫管理员禁用调试模式！不然无法正常更新模板！");
		}
        //获取域名信息
        $domain = Domain::find((int)$id);
        //获取域名属性
        $listsAttr = DomainAttr::where('did', $id)->get();
        $dataAttr = [];
        foreach ($listsAttr as $rowKey => $row) {
            $dataAttr[$row['call_tag']] = $row['value'];
        }
        //读取审核模板信息
        $sh_tpl_id = Group::where('id', $domain->gid)->value('sh_tpl_id');
        $sourceCodeCompany = htmlentities(Templates::where('id', $sh_tpl_id)->value('source_code'));
        $sourceCodeCompany = $this->replaceTpLable($dataAttr, $sourceCodeCompany);
        //把最新的模板保存到数据中
        $data['uid'] 		= $domain->uid;
        $data['username'] 	= $domain->username;
        $data['did'] 		= $domain->id;
        $data['gid'] 		= $domain->gid;
        $data['domain']		= $domain->domain;
		$time 				= time();
		$data['token'] 		= md5($userToken . $time);
		
        $url 				= $domain->access_type.'://'.$domain->domain."/upgrade.php";
		$newSkins = DB::table('new_skins');
		$newSkins->where('did', $domain->id)->delete();
		//保存审核模板
		$data['filename']	= 'company.php';//审核页文件名
        $data['html'] 		= $sourceCodeCompany;
        $data['term_id'] 	= Group::where('id',$domain->gid)->value('sh_term_id');
        $newSkins->insert($data);
		$data['directory']	= $domain->directory;
		$data['time'] 		= $time;
		$this->curlPost($url,$data);
		$data['token'] 		= md5($userToken . $time);
		//读取推广模板信息
		$tpl_ids 			= explode(',',$domain->tpl_id);
		$term_ids			= explode(',',Group::where('id',$domain->gid)->value('term_id'));//模板条件
		foreach($tpl_ids as $key=>$tpl_id){
			$temp				= Templates::where('id',$tpl_id)->value('source_code');
			unset($data['directory'],$data['time']);
			$data['filename']	= 'index'.($key+1).'.php';
			$data['html'] 		= $this->replaceTpLable($dataAttr,htmlentities($temp));
			$data['term_id'] 	= $term_ids[$key];
			$newSkins->insert($data);
			$data['directory']	= $domain->directory;
			$data['time'] 		= $time;
			$this->curlPost($url,$data);
		}
		if(httpcode($url)==200){
			event(new \App\Events\userActionEvent('\App\Models\Domain',$id, 3, '更新域名['.$domain->domain.']的模板'));
		}else{
			return "error";
		}
	}
	public function curlPost($url,$data){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	 protected function replaceTpLable($dataAttr, $sourceCode)
    {
        //循环替换模板标签属性
        foreach ($dataAttr as $key => $value) {
            $sourceCode = str_replace("{{" . $key . "}}", $value, $sourceCode);
        }
        $sourceCode = str_replace('{{$', "<?php echo \$data['", $sourceCode);
        $sourceCode = str_replace('$}}', "'];?>", $sourceCode);
        //清空不存在的值
        $sourceCode = preg_replace("/{{(.*?)}}/", '', $sourceCode);
        $sourceCode = html_entity_decode($sourceCode);
        return $sourceCode;
    }
}